<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>学习使用Promise</title>
  <style>
    .box{
      width: 50px;
      height: 50px;
      background: blueviolet;
    }
  </style>
</head>
<body>

<!-- --------------------------------------

  http://www.cnblogs.com/lhb25/archive/2013/03/05/jquery-deferred-promise.html
  http://www.cnblogs.com/lvdabao/p/es6-promise-1.html
  http://www.ruanyifeng.com/blog/2011/08/a_detailed_explanation_of_jquery_deferred_object.html

--------------------------------------- -->
<div class="box"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
// 例子1 --------------------------------------------------------------------
  var wait = function(){
    var dtd = $.Deferred(); //在函数内部，新建一个Deferred对象
    var tasks = function(){
      alert("执行完毕！");
      dtd.resolve(); // 改变Deferred对象的执行状态
    };

    setTimeout(tasks,5000);
    return dtd.promise(); // 返回promise对象
  };
  $.when(wait())
      .done(function(){ alert("哈哈，成功了！"); })
      .fail(function(){ alert("出错啦！"); });


// 例子2 ---------------------------------------------------------------------
var wait = function(defer){
  var tasks = function(){
    alert("执行完毕！");
    defer.resolve(); // 改变Deferred对象的执行状态
  };
  setTimeout(tasks,5000);
  return defer.promise();
};

$.Deferred(wait)
    .done(function(){ alert("哈哈，成功了！"); })
    .fail(function(){ alert("出错啦！"); });


// 例子3 ---------------------------------------------------------------------
$.when($.ajax( "/main.php" ))
    .then(successFunc, failureFunc );

  //.always 成功失败都会执行


</script>
</body>
</html>